package cn.danger.com.app;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import java.util.Map;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobConfig;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.danger.com.model.entity.MyUser;
import cn.danger.com.presenter.MemoPresenter;
import cn.danger.com.presenter.MemoPresenterImpl;
import cn.danger.com.presenter.SchedulePresenter;
import cn.danger.com.presenter.SchedulePresenterImpl;
import cn.danger.com.util.Check;
import cn.danger.com.util.Constants;
import cn.danger.com.util.FileCacheService;
import cn.danger.com.view.CommonView;

/**
 * Created by 俊 on 2016/12/29.
 */
public class MyApplication extends Application implements CommonView {

    private static int OPERATION_CODE;
    private MyReceiver receiver;
    private SchedulePresenter schedulePresenter;
    private MemoPresenter memoPresenter;

    @Override
    public void onCreate() {
        super.onCreate();

        initialize();
        login();
        receiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, intentFilter);

    }

    /**
     * 初始化Bmob配置
     */
    private void initialize() {
        BmobConfig.Builder builder = new BmobConfig.Builder(getApplicationContext());
        //设置appkey
        builder.setApplicationId("4bc3cd14840ba40207ba8e6ba90143bc");
        //设置请求超时时间，默认为15s
        builder.setConnectTimeout(30);
        //设置文件分片上传时每片的大小，默认为512*1024
        builder.setUploadBlockSize(1024 * 1024);
        //设置文件的过期时间，默认为1800s
        builder.setFileExpiration(2500);
        BmobConfig config = builder.build();
        Bmob.initialize(config);
//        Bmob.initialize(getApplicationContext(), "4bc3cd14840ba40207ba8e6ba90143bc");
//        dialog = new ProgressDialog(MyApplication.this, ProgressDialog.THEME_HOLO_LIGHT);
//        dialog.setMessage("正在执行...");
//        dialog.setCanceledOnTouchOutside(false);

        schedulePresenter = new SchedulePresenterImpl(getApplicationContext(), this);
        memoPresenter = new MemoPresenterImpl(getApplicationContext(), this);
    }

    private void login() {
        Log.i("danger", "执行一次");
        FileCacheService service = new FileCacheService(getApplicationContext());
        Map<String, String> map = (Map<String, String>) service.getSharePreference("userInfo");
        String phone = map.get("phone");
        String password = map.get("password");
        if (phone != null && password != null) {
            MyUser user = new MyUser();
            user.setUsername(phone);
            user.setPassword(password);
            user.login(new SaveListener<MyUser>() {
                @Override
                public void done(MyUser myUser, BmobException e) {
                    if (e == null) {
                        showMessage(Constants.SUCCESS_TO_AUTO_LOGIN);
                    } else {
                        Log.i("danger", e.getMessage());
                        if (Check.checkByCode(e.getErrorCode()) == null) {
                            showMessage(Constants.FAIL_TO_AUTO_LOGIN);
                        } else {
                            showMessage(Check.checkByCode(e.getErrorCode()));
                        }
                    }
                }
            });
        } else {
            OPERATION_CODE = Constants.NOT_LOGIN;
            showMessage(Constants.PLEASE_LOGIN);
        }
    }


    public static void setOperationCode(int code) {
        OPERATION_CODE = code;
    }

    public static int getOperateCode() {
        return OPERATION_CODE;
    }

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (networkInfo.isConnected() || wifiInfo.isConnected()) {
                OPERATION_CODE = Constants.NETWORK;
                showMessage(Constants.YOU_ARE_IN_NETWORK_MODEL);
                login();
            } else {
                OPERATION_CODE = Constants.LOCAL;
                showMessage(Constants.YOU_ARE_IN_LOCAL_MODEL);
            }
        }

    }

    @Override
    public void showDialog() {

    }

    @Override
    public void hideDialog() {

    }

    @Override
    public void showMessage(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
        if (message.equals(Constants.SUCCESS_TO_AUTO_LOGIN)) {
            schedulePresenter.synchronousSchedule();
            memoPresenter.synchronousMemo();
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
